//
//  LuckyNumberWnd.m
//  SMTools
//
//  Created by fengsh on 2019/1/6.
//  Copyright © 2019 fengsh. All rights reserved.
//

#import "LuckyNumberWnd.h"
#import "LuckyUtils.h"
#import "LuckyApi.h"
#import "LuckyNotifyWnd.h"
#import "LuckyResult.h"

@interface LuckyNumberWnd ()<NSTableViewDelegate,NSTableViewDataSource>
@property (nonatomic, strong) NSMutableArray                    *lunNumbers;
@property (nonatomic, strong) LuckyNotifyWnd                    *resultDisplay;
@end

@implementation LuckyNumberWnd

- (void)windowDidLoad {
    [super windowDidLoad];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:nil];
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    self.lunNumbers = [NSMutableArray array];
    
    for (int i = 0; i < self.currentProject.count; i++) {
        [self.lunNumbers addObject:[NSString stringWithFormat:@"第%d轮",i+1]];
    }
    
    [self.list reloadData];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.lunNumbers.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 40;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    if (colidx == 0) {
        for (NSButton *button in cv.subviews) {
            
            if ([button.identifier isEqualToString:@"btn_count"]) {
                [button setAction:@selector(onStartGo:)];
                [button setTitle:self.lunNumbers[row]];
            } else if ([button.identifier isEqualToString:@"btn_result"]) {
                [button setAction:@selector(onShowResult:)];
            }
            [button setTag:row];
            [button  setTarget:self];
            
        }
    } else {
        
        NSInteger total = self.currentProject.count; //总共轮数
        NSInteger remain = self.currentProject.remain_count; //剩余轮次
        
        BOOL isOk = (total - remain) > row;
        
        
        NSString *text = isOk ? @"已抽" : @"未抽奖";
        switch (colidx) {
            case 1:
            {
                [cv.textField setStringValue:text];
            }
                break;
           
            default:
                break;
        }
        
    }
    
    return cv;
}

- (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
{
    if (row % 2 != 0) {
        rowView.backgroundColor = [NSColor windowBackgroundColor];
    }
}

- (void)onStartGo:(NSButton *)sender
{
    NSInteger row = sender.tag;
    NSLog(@"开始抽奖第%ld轮",row+1);
    
    NSInteger total = self.currentProject.count;
    NSInteger remaincount = self.currentProject.remain_count;
    NSInteger current = (total - remaincount) + 1;
    if (current > total) { //不能操了
        NSLog(@"已抽过了，还点啥的点");
        return;
    }
    
    NSDictionary *p = @{@"prizeLevelId":@(self.currentProject.id),@"count":@(row+1)};
    [[LuckyApi api]lucky_api_post_queryLucyResult:p comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSString *code = respobj[@"retcode"];
            if ([code isEqualToString:@"00000"]) {
                self.currentProject.remain_count -= 1;
                [self.list reloadData];
            }
            else {
                NSString *msg = respobj[@"msg"];
                [LuckyUtils lucky_show:msg];
            }
        }
    }];
}

- (void)onShowResult:(NSButton *)sender
{
    NSInteger total = self.currentProject.count; //总共轮数
    NSInteger remain = self.currentProject.remain_count; //剩余轮次
    
    NSInteger row = sender.tag;
    
    BOOL isOk = (total - remain) > row;
    if (!isOk) {
        [LuckyUtils lucky_show:@"官人别急，该轮次还没开奖呢!"];
        return;
    }
    
    int64_t pid = self.currentProject.id;
    
    [[LuckyApi api]lucky_api_post_queryResultList:@{@"prizeLevelId":@(pid),@"prizedCount":@(row+1)} comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSString *rc = respobj[@"retcode"];
            if ([rc isEqualToString:@"00000"]) {
                NSArray *list = respobj[@"data"];
                NSMutableArray *godlist = [NSMutableArray array];
                for (NSDictionary *item in list) {
                    LuckyResult *rt = [[LuckyResult alloc]initWithContext:nil];
                    rt.id = [item[@"id"]longLongValue];
                    rt.name = [LuckyUtils lucky_dictionaryvalue:item[@"name"]];
                    rt.phone = [LuckyUtils lucky_dictionaryvalue:item[@"phone"]];
                    rt.email = [LuckyUtils lucky_dictionaryvalue:item[@"email"]];
                    rt.photo = [LuckyUtils lucky_dictionaryvalue:item[@"photo"]];
                    rt.prize_level_name = [LuckyUtils lucky_dictionaryvalue:item[@"prizeLevelName"]];
                    rt.prize_level_id = [item[@"prizeLevelId"]longLongValue];
                    rt.prized_count = (int32_t)[item[@"prizedCount"]integerValue];
                    [godlist addObject:rt];
                }
                
                self.resultDisplay = [[LuckyNotifyWnd alloc]initWithWindowNibName:@"LuckyNotifyWnd"];
                self.resultDisplay.currentProject = self.currentProject;
                self.resultDisplay.currentCount = row+1;
                self.resultDisplay.results = godlist;
                [self.resultDisplay.window center];
                [NSApp runModalForWindow:self.resultDisplay.window];
                
            } else {
                NSString *msg = respobj[@"msg"];
                [LuckyUtils lucky_show:msg];
            }
        } else {
            [LuckyUtils lucky_show:@"获取结果失败!请检测网络!"];
        }
    }];
    
  



    NSLog(@"显示操奖结果");
}

- (void)windowWillClose:(NSNotification *)notification
{
    NSWindow* window = notification.object;
    if (window == self.resultDisplay.window) {
        [NSApp stopModal];
        self.resultDisplay = nil;
    } 
}

@end
